/* protocol.c */

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#include "protocol.h"

static int fill_content(int id, const char *msg, int num,protocol_t *ptc){
	static char buf[256];
	strncpy(buf,msg, num);
	buf[num] = '\0';
	switch(id){
	case 1:	//action type
		if(num == 0 )
			return 0;
		ptc->act_type = atoi(buf);
		break;
	case 2:	//user id
		if(num == 0 )return 0;
		ptc->usr_id = atoi(buf);
		break;
	case 3:	//user name
		strcpy(ptc->usr_name, buf);
		break;
	case 4:	//user password
		strcpy(ptc->usr_pwd, buf);
		break;
	case 5:	//order num
		if(num == 0 )return 0;
		ptc->order_no = atoi(buf);
		break;
	case 6:	//start time
		//strptime(time,"%Y-%m-%d %H:%M:%S",&tim);
		if(num == 0 )return 0;
		ptc->time_start = (time_t)atol(buf);
		break;
	case 7:	//end time
		//strptime(time,"%Y-%m-%d %H:%M:%S",&tim);
		if(num == 0 )return 0;
		ptc->time_end = (time_t)atol(buf);
		break;
	case 8:
		if(num == 0 )return 0;
		ptc->ticket_id = atoi(buf);
		break;
	case 9:	//train no.
		strcpy(ptc->train_no, buf);
		break;
	case 10:	//ticket count
		if(num == 0 )return 0;
		ptc->ticket_count = atoi(buf);
		break;
	case 11:	//other infomation
		strcpy(ptc->other,buf);
		break;
	default:	//error
		return -1;
	}
	return 0;
}


/* |act_t|user id|usrname|pwd|order id|times|timee|ticketid|trainno|ticket num|other| */
int parse_msg(protocol_t *ptc, const char *msg){
	int i,start,end,count;
	empty_msg(ptc);
	if(msg[0] != '|')return -1;
	start = 1;
	count = 0;
	for(i =1;msg[i]!= '\0';i++){
		if(msg[i] == '|'){
			end = i;
			count ++;
			if(fill_content(count,msg+start, end - start, ptc) != 0)return -1;
			start = end +1;
		}
	}

	return 0;
}

int format_msg(protocol_t *ptc, char *msg){

	sprintf(msg,"|%d|%d|%s|%s|%d|%ld|%ld|%d|%s|%d|%s|",
			ptc->act_type,
			ptc->usr_id,
			ptc->usr_name,
			ptc->usr_pwd,
			ptc->order_no,
			ptc->time_start,
			ptc->time_end,
			ptc->ticket_id,
			ptc->train_no,
			ptc->ticket_count,
			ptc->other);

	return 0;
}

int empty_msg(protocol_t *ptc){
	if(ptc == NULL)return -1;
	ptc->act_type = 0;
	ptc->usr_id = 0;
	strcpy(ptc->usr_name,"");
	strcpy(ptc->usr_pwd,"");
	ptc->order_no = 0;
	ptc->time_start = 0;
	ptc->time_end = 0;
	ptc->ticket_id = 0;
	strcpy(ptc->train_no,"XXXX");
	ptc->ticket_count =0;
	strcpy(ptc->other,"");
	return 0;
}
